<?php
/**
 * Class handles mysql database communication.
 * @author Gustav Knutsson
 */
class jdDatabaseMySql{
	// Holds THIS instance, Singleton pattern
	private static $instance;
	
	// Holds the affected rows number, after doing a this::statement
	public $AFFECTED_ROWS;
	
	// Holds last insert ID, after doing a this::statement using INSERT INTO
	public $LAST_ID;
	
	/**
	 * Class construct, private to support the singleton pattern
	 */
	private function __construct(){ }
	
	/**
	 * Returns instance of this object
	 * @return Object jdDatabaseMySql
	 * 
	 * @author Gustav Knutsson
	 */
	public function getInstance(){
		if(!isset(self::$instance)){
			$c = __CLASS__;
			self::$instance = new $c;
			
			self::Connect();
		}
		
		return self::$instance;
	}
	
	/**
	 * Connects to the MySql database...
	 * $author Gustav Knutsson
	 */
	private function Connect(){
		$con = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD);
		if(!$con){
			die("<b>jdError:</b> Mysql connect failed with error:<br />".mysql_error());
		}
		mysql_select_db(MYSQL_DATABASE) or die("<b>jdError:</b> Failed to select mysql database '".MYSQL_DATABASE."'");
	}
	
	/**
	 * Fetches data from the database and returns it as array
	 * @param String $sql
	 * 
	 * @return Array
	 * @author Gustav Knutsson
	 */
	public function fetch($sql){
		$q = mysql_query($sql) or die("<b>jdError:</b> Mysql query failed:<br />".mysql_error());
		
		$arr = array();
		while($r = mysql_fetch_array($q)){
			$arr[] = $r;
		}
		
		return $arr;
	}
	
	/**
	 * Do statement in mysql eg. DELETE, UPDATE, INSERT
	 * @param String $sql
	 * 
	 * @author Gustav Knutsson
	 */
	public function statement($sql){
		$q = mysql_query($sql) or die("<b>jdError:</b> Mysql query failed:<br />".mysql_error());
		$this->AFFECTED_ROWS = mysql_affected_rows();
		
		if(substr_count(strtoupper($sql),"INSERT INTO") > 0){
			$this->LAST_ID = mysql_insert_id();
		}
	}
}
?>